import { takeUntil } from 'rxjs/operators';

import { MessageReceiveData } from './interface';
import { MessageListenersManager } from './message-listeners-manager';
import { ReceiveArgumentsType } from './message-ts-util';

export function MessageListener<T extends keyof MessageReceiveData>(type: T): Function {
  return (target: MessageListenersManager, propertyKey: string, descriptor: TypedPropertyDescriptor<ReceiveArgumentsType<T>>) => {
    // 获取构造上的静态属性 __messageListeners__
    const constructor = Object.getPrototypeOf(target).constructor;
    if (constructor && constructor.__messageListeners__) {
      // 将创建订阅的方法推入 __messageListeners__ , 以便在构造时调用
      constructor.__messageListeners__.push([
        target.constructor,
        function (this: any): void {
          // 创建指定类型的订阅
          this.messageService
            .receive(type)
            // 使用 takeUntil  操作符以便自动取消订阅
            .pipe(takeUntil(this.__messageListenersTakeUntilDestroy$__))
            .subscribe((data: any) => {
              const baz = descriptor.value as Function;
              baz?.call(this, data);
            });
        }
      ]);
    }
    return descriptor;
  };
}
